<template>
    <div class="article-con">
        <el-row class="article-header" type="flex">
            <el-col :span="18">
                <el-input v-model="title" placeholder="输入文章标题..." class="title-input"></el-input>
            </el-col>
            <el-col :span="2">
                <el-popover
                        placement="bottom-end"
                        width="330"
                        trigger="click">
                    <div class="publish-pannel">
                        <h2 style="margin-bottom: 14px">添加封面大图</h2>
                        <el-upload
                                class="avatar-uploader"
                                :action="$http.defaults.baseURL+'/upload'"
                                :show-file-list="false"
                                :on-success="handleUploadArticleImg">
                            <img v-if="imageUrl" :src="imageUrl" class="avatar">
                            <button v-else class="select-btn">点击此处添加图片</button>
                        </el-upload>
                    </div>
                    <img src="../../assets/img/upload.png" slot="reference">
                </el-popover>
            </el-col>
            <el-col :span="2">
                <el-popover
                        placement="bottom-end"
                        width="330"
                        trigger="click">
                    <div class="publish-pannel">
                        <h2>发布文章</h2>
                        <p class="subtitle">分类</p>
                        <div>
                            <div v-for="(item,i) in categories" class="categories-item" :class="{active:i==activeIndex}"
                                 :key="i"
                                 @click="onclick_choseCate(i,item)">{{item.cateName}}
                            </div>
                        </div>
                        <button class="publish-btn" @click="onclick_submit">确定发布</button>
                    </div>
                    <el-button slot="reference">发布</el-button>
                </el-popover>
            </el-col>
            <el-col :span="2">
                <User :user="userInfo" style="justify-content: flex-end"></User>
            </el-col>
        </el-row>
        <div class="mavonEditor">
            <mavon-editor
                    ref="md"
                    :toolbars="markdownOption"
                    v-model="content"
                    :ishljs="true"
                    class="w100 h100"
                    @imgAdd="imgAdd"
                    :codeStyle="codeStyle"/>
        </div>
    </div>
</template>

<script>
    import User from "@/components/User.vue";
    import {toolbars} from "@/plugins/vue-mavon-editor";
    import hljs from 'highlight.js' //导入代码高亮文件
    import 'highlight.js/styles/googlecode.css'
    import * as qiniu from 'qiniu-js'

    async function highlightHandle() {
        await hljs;
        let highlight = document.querySelectorAll('pre code');
        highlight.forEach((block) => {
            hljs.highlightBlock(block)
        })
    }

    highlightHandle()
    export default {
        name: "new",
        layout: "login",
        components: {
            User
        },
        computed: {
            userInfo() {
                return this.$store.state.user;
            },
        },
        data() {
            return {
                title: "",
                categories: [],
                content: "",
                activeIndex: null,
                category: null,
                imageUrl: "",
                markdownOption: toolbars,
                codeStyle: "monokai"
            }
        },
        async created() {
            let res = await this.$http.get("/categories");
            this.categories = res.data;
            // 去服务端生成七牛token
            this.fetchUploadToken()
        },
        methods: {
            async onclick_submit() {
                let res = await this.$http.post("/article/create", {
                    title: this.title,
                    content: this.content,
                    category: this.category,
                    coverImage: this.imageUrl
                })
                if (res.code == 0) {
                    this.$message.success(`文章《${res.data.title}》创建成功！`);
                    setTimeout(() => {
                        this.$router.push({path: "/article/" + res.data.id})
                    })
                }
            },
            onclick_choseCate(i, cate) {
                this.activeIndex = i;
                this.category = cate._id
            },
            // 点击上传文章封面大图
            handleUploadArticleImg(res) {
                console.log(res)
                this.imageUrl = res.url;
            },
            async fetchUploadToken() {
                let res = await this.$http.get('/getQiniuToken')
                this.token = res.data;
                console.log(this.token)
            },

            imgAdd(pos, file) {
                this.file = file
                this.pos = pos
                let key = this.file.name
                // 调用七牛的接口将图片上传至七牛
                let observable = qiniu.upload(this.file, key, this.token)
                observable.subscribe(this.uploadNext, this.uploadError, this.uploadComplete)
                return false
            },
            uploadNext(res) {
                // ...
            },
            uploadError(err) {
                alert(err)
            },
            uploadComplete(res) {
                // 取得七牛返回的url
                let url = 'http://qd5jgbex8.bkt.clouddn.com/' + res.key
                // 将url插入markdown
                this.$refs.md.$img2Url(this.pos, url)
            }

        }

    }
</script>

<style scoped lang="less">
    .article-con {
        background-color: #ffffff;
    }

    .article-header {
        height: 63px;
        padding-left: 16px;
        border-bottom: 1px solid #dddddd;
    }

    /deep/
    .el-popover {
        padding: 20px;
    }

    /deep/
    .el-upload {
        width: 100%;

        img {
            width: 100%;
        }
    }

    .publish-pannel {
    }

    .el-col {
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .title-input {
        height: 100%;

        /deep/
        .el-input__inner {
            border: none;
            line-height: 63px;
            height: 100%;
            font-size: 20px;
            color: #000000;
            font-weight: bold;
        }
    }

    .categories-item {
        margin: 0 7px 9px 0;
        display: inline-block;
        white-space: nowrap;
        border: 1px solid #f1f1f1;
        border-radius: 2px;
        cursor: pointer;
        padding: 4px 8px;
    }

    .categories-item:hover, .active {
        color: #007fff;
        border-color: rgba(0, 127, 255, .15);
        background-color: rgba(0, 127, 255, .05)
    }


    .publish-btn {
        display: block;
        margin: 0 auto;
        padding: .6rem 1.2rem;
        color: #007fff;
        background: #ffffff;
        border: 1px solid currentColor;
        border-radius: 2px;
        outline: none;
        cursor: pointer;
        transition: all .2s;
    }

    .subtitle {
        margin: 10px 0;
    }

    .md-editor {
        width: 100%;
        height: 100vh;
        padding: 20px;
        background-color: #f8f9fa;
        border: none;
        border-right: 1px solid #dddddd;
    }

    .markdown-display {
        padding: 20px;
    }

    .select-btn {
        width: 100%;
        height: 6rem;
        font-size: 1.334rem;
        color: rgba(51, 51, 51, .4);
        background-color: hsla(0, 0%, 87%, .6);
        border: none;
        outline: none;
        cursor: pointer;
    }

    .mavonEditor {
        width: 100%;
        height: 100vh;
    }
</style>
